package mongo

import (
	"context"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"login/src/conf"
	"time"
)

var (
	DBMongo         *mongo.Database
	CollectionUsers *mongo.Collection
)

func Init() {
	// 使用 Connect 方法初始化客户端
	cfg := conf.GetConf().Mongo
	client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(cfg.URI))
	if err != nil {
		log.Fatal("Failed to connect to DBMongo:", err)
	}

	// 测试连接
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	err = client.Ping(ctx, nil)
	if err != nil {
		log.Fatal("Ping to DBMongo failed:", err)
	}

	// 获取数据库和集合
	DBMongo = client.Database("testdb")

	CollectionUsers = DBMongo.Collection("users")
}
